<template>
  <!-- 安全责任书回执 -->
  <div class="resporeceipt">
    <basic-container>
      <avue-crud
        :option="option"
        :table-loading="loading"
        :data="data"
        :page.sync="page"
        :permission="permissionList"
        ref="crud"
        v-model="form"
        :before-open="beforeOpen"
        @search-change="searchChange"
        @search-reset="searchReset"
        @selection-change="selectionChange"
        @current-change="currentChange"
        @size-change="sizeChange"
        @refresh-change="refreshChange"
      >

        <!-- 搜索栏 -->
        <template slot="searchMenu">
          <el-radio-group v-model="receiptType" style="float: right;">
            <el-radio-button :label="allStr">所有回执书</el-radio-button>
            <el-radio-button :label="myStr">我的回执书</el-radio-button>
          </el-radio-group>
        </template>

        <!-- 责任书下载列表格自定义 -->
        <template slot="safetyPostRespoId" slot-scope="scope">
          <div class="enclosure_div" v-if="scope.row['zrs'] && scope.row['zrs'].length !== 0">
            <a 
              v-for="(item, index) in scope.row['zrs']" 
              :key="index"
              :href="downloadHead + item.id" >
              <p><i class="el-icon-download"></i>下载责任书{{index + 1}}</p>
            </a>
          </div>
          <span v-else>-</span>
        </template>

        <!-- 责任书下载表单自定义 -->
        <template slot="safetyPostRespoIdForm">
          <div v-if="zrsFileList.length !== 0">
            <a
              v-for="(item, index) in zrsFileList"
              :key="index"
              :href="downloadHead + item.response.data.id"
              style="color:#409EFF"
            >
              <p style="margin-top: 0px; margin-bottom: 0px;">
                <i class="el-icon-download" style="margin-right:5px;"></i>下载责任书（{{ item.name }}）
              </p>
            </a>
          </div>
          <span v-else>-</span>
        </template>

        <!-- 回执下载列表格自定义 -->
        <template slot="zrshzfj" slot-scope="scope">
          <div class="enclosure_div" v-if="scope.row['hz'] && scope.row['hz'].length !== 0">
            <a 
              v-for="(item, index) in scope.row['hz']" 
              :key="index"
              :href="downloadHead + item.id" >
              <p><i class="el-icon-download"></i>下载回执{{index + 1}}</p>
            </a>
          </div>
          <span v-else>-</span>
        </template>

        <!-- 回执下载表单自定义 -->
        <template slot="zrshzfjForm">
          <div v-if="hzdFileList.length !== 0">
            <a
              v-for="(item, index) in hzdFileList"
              :key="index"
              :href="downloadHead + item.response.data.id"
              style="color:#409EFF"
            >
              <p style="margin-top: 0px; margin-bottom: 0px;">
                <i class="el-icon-download" style="margin-right:5px;"></i>下载回执（{{ item.name }}）
              </p>
            </a>
          </div>
          <span v-else>-</span>
        </template>

        <!-- 考核结果列表格自定义 -->
        <template slot="khjg" slot-scope="scope">
          <span>{{formatAssessStatus(scope.row)}}</span>
        </template>

        <!-- 考核结果表单自定义 -->
        <template slot="khjgForm" slot-scope="scope">
          <span>{{formatAssessStatus(scope.row)}}</span>
        </template>

        <!-- 考核列表格自定义 -->
        <template slot="assess" slot-scope="scope">
          <div>
            <el-button
              v-if="scope.row['assessorAuthority'] === true && scope.row['zrshzfj'] !== '' && scope.row['sfkh'] === 0"
              type="warning"
              size="mini"
              icon="el-icon-edit-outline"
              @click="handleAssess(scope.row)">
              考 核
            </el-button>
            <el-button
              v-else-if="scope.row['assessorAuthority'] === true && scope.row['zrshzfj'] !== '' && scope.row['sfkh'] === 1"
              type="primary"
              size="mini"
              icon="el-icon-document-checked"
              @click="handleReAssess(scope.row)">
              重新考核
            </el-button>
            <span v-else>-</span>
          </div>
        </template>

        <!-- 回执上传列表格自定义 -->
        <template slot="uploadHZ" slot-scope="scope">
          <el-button 
            size="mini"
            type="success"
            icon="el-icon-upload2"
            @click="handleUploadReceipt(scope.row)">
            上传回执
          </el-button>
        </template>

      </avue-crud>

      <!-- 弹窗：上传回执 -->
      <el-dialog 
        title="上传回执"
        append-to-body
        :visible.sync="uploadReceiptDialog"
        :close-on-click-modal="false" 
        :before-close="closeUploadReceiptDialog"
        width="60%"
        class="upload_receipt_dialog"
      >

        <!-- 内容 -->
        <avue-form 
          ref="uploadForm" 
          v-model="uploadObj" 
          :option="uploadOption" 
          @submit="confirmUpload"
        >

          <!-- 上传回执表单自定义 -->
          <template slot="zrshzfj">
            <div>
              <el-upload
                action="/api/fileManager/upload/file"
                :headers="SetHeaders"
                :file-list="schzFileList"
                :before-upload="beforeUploadSCHZ"
                :on-remove="handleRemoveSCHZ"
                :on-success="uploadSCHZSuccess"
              >
                <el-button 
                  size="small" 
                  type="primary" 
                  icon="el-icon-document">
                  选择回执
                </el-button>
              </el-upload>
            </div>
          </template>

          <!-- 自定义按钮 -->
          <template slot="menuForm">
            <el-button 
              size="small"
              icon="el-icon-close"
              @click="closeUploadReceiptDialog()">
              取 消
            </el-button>
          </template>

        </avue-form>
      </el-dialog>

      <!-- 弹窗：考核&重新考核 -->
      <el-dialog 
        :title="dialogTitle"
        append-to-body
        :visible.sync="assessDialog"
        :close-on-click-modal="false" 
        :before-close="closeAssessDialog"
        width="60%"
        class="assess_dialog"
      >
        <avue-form 
          ref="assessForm" 
          v-model="assessObj" 
          :option="assessOption" 
          @submit="confirmAssess"
        >
          <template slot="menuForm">
            <el-button 
              size="small"
              icon="el-icon-close"
              @click="closeAssessDialog()">
              取 消
            </el-button>
          </template>
        </avue-form>
      </el-dialog>

    </basic-container>
  </div>
</template>

<script>
import {
  getList,
  update,
  uploadReceipt
} from "@/api/duty/dutiesandresponsibilities/resporeceipt";
import { mapGetters } from "vuex";
import { getToken } from "@/util/auth";

const tenantId = JSON.parse(localStorage.getItem("saber-tenantId")).content;

export default {
  data() {
    return {
      form: {},
      query: {},
      data: [],
      loading: true,
      selectionList: [],
      page: {
        pageSize: this.$pageSize,
        currentPage: 1,
        total: 0
      },
      option: {
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchSpan: 6,
        searchMenuSpan: 18,
        border: true,
        addBtn: false,
        index: false,
        selection: false,
        viewBtn: true,
        editBtn: false,
        delBtn: false,
        refreshBtn: true,
        columnBtn: false,
        dialogClickModal: false,
        menuWidth: 120,
        column: [
          {
            label: "岗位名称",
            prop: "postId",
            align: "center",
            width: 150,
            type: "select",
            dicUrl: "/api/blade-system/post/select?tenantId=" + tenantId,
            props: {
              label: "postName",
              value: "id",
            }
          },
          {
            label: "姓名",
            prop: "userId",
            align: "center",
            width: 150,
            search: true,
            type: "select",
            dicUrl: "/api/riskPoint/riskmanagement/getInternalStaff",
            props: {
              label: "realName",
              value: "id",
            }
          },
          {
            label: "电话",
            prop: "phone",
            align: "center"
          },
          {
            label: "签订时间",
            prop: "zrqdsj",
            align: "center",
          },
          {
            label: "责任书下载",
            prop: "safetyPostRespoId",
            align: "center",
            slot: true,
            formslot: true
          },
          {
            label: "回执下载",
            prop: "zrshzfj",
            align: "center",
            slot: true,
            formslot: true
          },
          {
            label: "回执上传",
            prop: "uploadHZ",
            align: "center",
            width: 150,
            hide: true,
            display: false,
            slot: true
          },
          {
            label: "考核结果",
            prop: "khjg",
            hide: false,
            align: "center",
            slot: true,
            formslot: true
          },
          {
            label: "考核",
            prop: "assess",
            hide: false,
            align: "center",
            width: 150,
            slot: true,
            display: false
          }
        ]
      },
      receiptType: "ALL",
      allStr: "ALL",
      myStr: "MY",
      zrsFileList: [],
      hzdFileList: [],
      assessResult: {
        1: "优",
        2: "良",
        3: "中",
        4: "差"
      },
      // 附件
      downloadHead: "/api/fileManager/download/",
      SetHeaders: { "Blade-Auth": getToken() },
      // 弹窗：上传回执
      uploadReceiptDialog: false,
      uploadObj: {},
      schzFileList: [],
      // 弹窗：考核&重新考核
      assessDialog: false,
      assessObj: {}
    };
  },
  computed: {
    ...mapGetters(["permission"]),

    // 按钮权限
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.resporeceipt_add, false),
        viewBtn: this.vaildData(this.permission.resporeceipt_view, false),
        delBtn: this.vaildData(this.permission.resporeceipt_delete, false),
        editBtn: this.vaildData(this.permission.resporeceipt_edit, false)
      };
    },

    // 勾选项ID
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push(ele.id);
      });
      return ids.join(",");
    },

    // 弹窗：上传回执
    uploadOption() {
      return {
        size: "small",
        submitText: "确 定",
        mockBtn: false,
        printBtn: false,
        emptyBtn: false,
        column: [
          {
            label: "上传回执",
            prop: "zrshzfj",
            slot: true,
            formslot: true,
            span: 24,
            rules: [{
              required: true,
              message: "请选择至少一个回执",
              trigger: "change"
            }]
          }
        ]
      }
    },

    // 弹窗：考核&重新考核
    assessOption() {
      return {
        size: "small",
        submitText: "确 定",
        mockBtn: false,
        printBtn: false,
        emptyBtn: false,
        column: [
          {
            label: "考核结果",
            prop: "khjg",
            span: 24,
            type: "select",
            dicData: [{
              label: "优",
              value: 1
            }, {
              label: "良",
              value: 2
            }, {
              label: "中",
              value: 3
            }, {
              label: "差",
              value: 4
            }],
            rules: [{
              required: true,
              message: "请选择考核结果",
              trigger: "change"
            }]
          },
          {
            label: "考核情况",
            prop: "khqk",
            span: 24,
            type: "textarea",
            maxLength: 250
          }
        ]
      }
    }
  },
  watch: {
    receiptType(){
      if(this.receiptType === this.allStr){
        this.query["type"] = "";
        // 回执上传
        this.findObject(this.option.column, "uploadHZ").hide = true;
        // 考核结果
        this.findObject(this.option.column, "khjg").hide = false;
        // 考核
        this.findObject(this.option.column, "assess").hide = false;
      } else if(this.receiptType === this.myStr) {
        this.query["type"] = this.allStr;
        this.findObject(this.option.column, "uploadHZ").hide = false;
        this.findObject(this.option.column, "khjg").hide = true;
        this.findObject(this.option.column, "assess").hide = true;
      }
      this.page.currentPage = 1;
      this.onLoad(this.page);
    }
  },
  mounted() {
    this.initData();
  },
  methods: {

    // 初始化数据
    initData() {
      this.onLoad(this.page);
    },

    // 格式化考核结果
    formatAssessStatus(row) {
      var khjg = row.khjg;
      if(khjg === "" || khjg === null || khjg === undefined || this.assessResult[khjg] === undefined) {
        return "未考核";
      } else {
        return this.assessResult[khjg];
      }
    },

    // 打开查看弹窗前
    beforeOpen(done, type) {
      this.zrsFileList = [];
      this.hzdFileList = [];
      if(type === "view") {
        if(this.form.zrsfj && this.form.zrs && JSON.stringify(this.form.zrs) !== "[]") {
          this.form.zrs.forEach(item => {
            this.zrsFileList.push({
              name: item.fileName,
              response: {
                code: 200,
                msg: "操作成功",
                success: true,
                data: item
              }
            });
          });
        }
        if(this.form.zrshzfj && this.form.hz && JSON.stringify(this.form.hz) !== "[]") {
          this.form.hz.forEach(item => {
            this.hzdFileList.push({
              name: item.fileName,
              response: {
                code: 200,
                msg: "操作成功",
                success: true,
                data: item
              }
            });
          });
        }
      }
      done();
    },
    
    // 清空搜索条件
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },

    // 搜索条件改变
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },

    // 勾选
    selectionChange(list) {
      this.selectionList = list;
    },

    // 清空勾选
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },

    // 更换页数
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
      this.onLoad(this.page);
    },

    // 更换每页显示数量
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
      this.onLoad(this.page);
    },

    // 刷新
    refreshChange() {
      this.onLoad(this.page, this.query);
    },

    // 加载数据
    onLoad(page, params = {}) {
      this.loading = true;
      getList(
        page.currentPage,
        page.pageSize,
        Object.assign(params, this.query)
      ).then(res => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
      });
    },

    /**
     * 上传回执
     */

    // 上传回执前
    beforeUploadSCHZ(file) {
      console.log(file);
      var isLimit = this.schzFileList.length + 1 <= 2;
      if (!isLimit) {
        this.$message.warning("最多选择两个回执!");
      }
      return isLimit;
    },

    // 上传回执成功
    uploadSCHZSuccess(response, file, fileList) {
      if (response.code !== 200 || response.success !== true) {
        return;
      }
      this.schzFileList = fileList;
      this.uploadObj.zrshzfj = this.formatFormSCHZ(this.schzFileList);
    },

    // 删除回执
    handleRemoveSCHZ(file, fileList) {
      this.schzFileList = fileList;
      this.uploadObj.zrshzfj = this.formatFormSCHZ(this.schzFileList);
    },

    // 获取回执ID
    formatFormSCHZ(fileList) {
      var fileIds = [];
      fileList.forEach(item => {
        fileIds.push(item.response.data.id);
      });
      return fileIds.join(",");
    },

    /**
     * 弹窗：上传回执
    */

    // 打开上传回执弹窗
    handleUploadReceipt(row) {
      this.uploadObj = {
        id: row.id, 
        zrshzfj: row.zrshzfj ? "" : row.zrshzfj
      };
      this.schzFileList = [];
      this.uploadReceiptDialog = true;
      if(row.zrshzfj && row.hz && JSON.stringify(row.hz) !== "[]") {
        row.hz.forEach(item => {
          this.schzFileList.push({
            name: item.fileName,
            response: {
              code: 200,
              msg: "操作成功",
              success: true,
              data: item
            }
          });
        });
      }
    },

    // 确定上传回执
    confirmUpload() {
      this.$refs.uploadForm.validate((vaild,done)=>{
        if(vaild){
          uploadReceipt(this.uploadObj.id, this.uploadObj.zrshzfj).then(res => {
            if(res.data.success) {
              this.closeUploadReceiptDialog();
              this.page.currentPage = 1;
              this.onLoad(this.page);
            }
          });
          done();
        }
      })
    },

    // 取消、关闭上传回执弹窗
    closeUploadReceiptDialog() {
      this.uploadObj = {};
      this.schzFileList = [];
      this.uploadReceiptDialog = false;
    },

    /**
     * 弹窗：考核&重新考核
    */

    // 获取考核&重新考核数据
    formatAssessObj(row) {
      var data = {};
      for(var key in row) {
        data[key] = row[key];
      }
      return data;
    },

    // 打开考核弹窗
    handleAssess(row) {
      this.dialogTitle = "考核";
      this.assessObj = this.formatAssessObj(row);
      this.assessDialog = true;
    },

    // 打开重新考核弹窗
    handleReAssess(row) {
      this.dialogTitle = "重新考核";
      this.assessObj = this.formatAssessObj(row);
      this.assessDialog = true;
    },

    // 确定考核&重新考核
    confirmAssess() {
      this.$refs.assessForm.validate((vaild,done)=>{
        if(vaild){
          update(this.assessObj).then(res => {
            if(res.data.success) {
              this.closeAssessDialog();
              this.page.currentPage = 1;
              this.onLoad(this.page);
            }
          });
          done();
        }
      })
    },

    // 关闭、取消考核&重新考核弹窗
    closeAssessDialog() {
      this.dialogTitle = "";
      this.assessObj = {};
      this.assessDialog = false;
    }

  }
};
</script>

<style lang="scss" scpoed>
.resporeceipt {
  .avue-crud__search {
    .avue-form__row {
      .el-form-item {
        .el-form-item__label {
          width: 50px !important;
        }

        .el-form-item__content {
          margin-left: 50px !important;
        }
      }
    }
  }

  .enclosure_div {
    a {
      font-size: 12px;
      color: #409eff;

      p {
        margin-top: 0px;
        margin-bottom: 0px;
      }

      i {
        margin-right: 5px;
      }
    }
  }
}

.upload_receipt_dialog,
.assess_dialog {
  .avue-form__menu--center {
    text-align: center;
  }
}
</style>